<template>
  <el-row>
    <el-col :span="24">
      <el-upload
        class="w-16 h-16 b-rd bg-#f2f5f7"
        :show-file-list="false"
        :before-upload="beforeFileUpload"
        :http-request="customHttpRequest"
      >
        <div class="text-center lh-19 w-16 h-16">
          <el-icon :size="24"><Plus /></el-icon>
        </div>
      </el-upload>
    </el-col>
    <el-col v-for="(item, index) in modelValue" :key="index" :span="24">
      <div
        class="flex p-0.5 w-300px bg-#f2f5f7 mt-1 pl-2 pr-2 flex-items-center flex-justify-between"
      >
        <el-tooltip effect="dark" :content="item.fileName" placement="top-start">
          <div
            class="overflow-hidden text-ellipsis whitespace-nowrap color-#409eff cursor-pointer"
            @click="downloadFile(item)"
          >
            {{ item.fileName }}
          </div>
        </el-tooltip>
        <el-popconfirm
          title="确认删除文件？"
          placement="top-start"
          @confirm="deleteFile(item, index)"
        >
          <template #reference>
            <el-icon :size="14" class="cursor-pointer"><Delete /></el-icon>
          </template>
        </el-popconfirm>
      </div>
    </el-col>
  </el-row>
</template>

<script setup lang="ts">
import { Plus } from '@element-plus/icons-vue'
import { uploadFile, delFile } from '@/api/upload'
import { type IUploadResult } from '@/api/upload/types'
import { computed } from 'vue'
import type { UploadRequestOptions } from 'element-plus'
import { getCurrentInstance } from 'vue'
const { proxy } = getCurrentInstance() as any
const props = withDefaults(defineProps<{ modelValue: IUploadResult[] }>(), {
  modelValue: () => [],
})
const fileList = computed({
  get() {
    return props.modelValue || []
  },
  set(value) {
    emit('update:modelValue', value)
  },
})
const emit = defineEmits(['update:modelValue'])
const beforeFileUpload = async (file: File) => {
  return Promise.resolve()
}
const customHttpRequest = async (option: UploadRequestOptions) => {
  const { file } = option
  try {
    const res:any = await uploadFile(file)
    if (res.code === 200) {
      proxy ? proxy.$modal.msgSuccess('上传成功') : null
      const newFileList = [...fileList.value, { ...res.data }]
      fileList.value = newFileList // 触发响应式更新
    }
  } catch (error) {}
}

const deleteFile = async (item: IUploadResult, index: number) => {
  try {
    const res:any = await delFile(item.ossId)
    if (res.code === 200) {
      proxy ? proxy.$modal.msgSuccess('删除成功') : null
      fileList.value.splice(index, 1)
    }
  } catch (error) {}
}
const downloadFile = (item: IUploadResult) => {
  window.open(item.url, '_blank')
}
</script>
<style scoped></style>
